<?php

/**
 * Description of Money.
 * Handles storing, displaying and arithmetic of money.
 *
 * @author Ian Clarence <ian.clarence@gmail.com>
 */
class Money {

    /**
     * Money will be stored in tha database as an integer:
     * e.g. in pence or cents.
     * @var int
     */
    private $storedAmount;

    /**
     * The currency code: e.g. GBP, USD, EUR, etc.
     * @var string
     */
    private $currencyCode;

    /**
     * The constructor.
     *
     * @param float $amount
     * @param string $currencyCode
     * @return bool 
     */
    public function __construct(
        float $amount = 0,
        string $currencyCode = "GBP"
    ) {
        if ($this->validate($amount)) {
            $this->storedAmount = $amount * 100;
            $this->currencyCode = $currencyCode;
            return TRUE;
        }
        return FALSE;
    }

    /**
     * Returns integer to be stored in the database.
     *
     * @return int
     */
    public function store() {
        return $this->storedAmount;
    }

    /**
     * Returns a string for displaying an amount of money on a webpage.
     *
     * @param bool $showCurrencyCode
     * @return string
     */
    public function format($showCurrencyCode = FALSE) {
        return sprintf("%01.2f", $this->storedAmount / 100) . ($showCurrencyCode ? $this->currencyCode : "");
    }

    /**
     * Adding or subtracting.
     *
     * @param float $amount
     * @return bool
     */
    public function add(float $amount) {
        if ($this->validate($amount)) {
            $this->storedAmount += $amount * 100;
        }
        return FALSE;
    }

    /**
     * Multiplying and rounding if necessary.
     *
     * @param float $factor
     * @param int $precision
     * @param int $mode
     */
    public function multiply(float $factor, int $precision = 0, int $mode = PHP_ROUND_HALF_UP) {
        $this->storedAmount = round($this->storedAmount * $factor);
    }

    /**
     * Validation of an amount of money: Multiplication by 100 must give an integer.
     *
     * @param float $amount
     * @return bool
     */
    private function validate(float $amount) {
        return is_int($amount * 100);
    }
}

